package cn.hchaojie.camp.day12;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DemoSynchorized {
	public static void main(String[] args) throws InterruptedException {
		Counter counter = new Counter();
		
		// 多个线程去改同样一个对象
		ExecutorService service = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 3; i++) {
			// 每个线程会把计数器+1
			service.execute(new CounterRunnable(counter));
		}
				
		Thread.sleep(2000);
		
		// 计数结束
		System.out.println(counter.getCount());

		service.shutdown();
	}
}

class CounterRunnable implements Runnable {
	private Counter c;
	public CounterRunnable(Counter c) {
		this.c = c;
	}

	@Override
	public void run() {
		c.count();
	}
}

class Counter {
	private int count = 0;
	
	public synchronized void count() {
		try {
			Thread.sleep(80);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.count = this.count + 1;
	}

	public synchronized int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}
}
